package xj.graph2d.app.prop;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JToggleButton;

import xj.graph2d.Command;
import xj.graph2d.DrawAttr;
import xj.graph2d.DrawCanvas;
import xj.graph2d.DrawShape;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.TextShape;
import xj.graph2d.command.SetAttrCommand;

public class TextListener 
  extends AttrListener 
  implements ActionListener {

  public void actionPerformed(ActionEvent e) {
    if (e != null) {
      Object src = e.getSource();
      if (src != null && src instanceof JToggleButton) {
	JToggleButton b = (JToggleButton) src;
	SimpleDrawView view = main.getView();
	SimpleDrawDocument doc = main.getDoc();
	String cmd = b.getActionCommand();

	if (updateSystemAttr) {
	  if ("Underline".equals(cmd)) {
	    view.setUnderlined(b.isSelected());
	  } else if ("Bold".equals(cmd)) {
	    view.setBoldFont(b.isSelected());
	  } else if ("Italic".equals(cmd)) {
	    view.setItalicFont(b.isSelected());
	  }
	}

	DrawShape shape = doc.getSelectedShape();
	if (shape instanceof TextShape) {
	  DrawAttr attr = shape.getDrawAttr();
	  if (attr != null) {
	    Command command = new SetAttrCommand(view, doc, shape);
	    doc.addCommand(command);

	    DrawCanvas canvas = view.getCanvas();
	    DrawShape parent = shape.getParent();
	    if (parent == null) {
	      doc.remove(shape);
	    } else {
	      parent.removeShape(shape);
	    }
	    Rectangle2D r = shape.getBounds();
	    canvas.repaintRect(r, true, true);
	    if ("Underline".equals(cmd)) {
	      attr.setUnderlined(b.isSelected());
	    } else if ("Bold".equals(cmd)) {
	      attr.setBoldFont(b.isSelected());
	    } else if ("Italic".equals(cmd)) {
	      attr.setItalicFont(b.isSelected());
	    }
	    if (parent == null) {
	      doc.add(shape, true);
	    } else {
	      parent.addShape(shape, true);
	    }
	    shape.calculateBounds();
	    canvas.repaintShape(shape);
	  }
	}
      }
    }

  }

}
